(function() {
  var Config, Fs, ImportFiles, ImportFilesObjs, MergerFiles, Path, staticPrefix, version, _;

  _ = require('underscore');

  Path = require('path');

  Fs = require('fs');

  Config = require('../config');

  ImportFilesObjs = {};

  staticPrefix = Config.server.staticPrefix;

  version = new Date().getTime();

  MergerFiles = {
    getMergerFile: function(file, type) {
      var mergerFile, searchFiles, self;
      self = this;
      mergerFile = '';
      if (type === 'css') {
        searchFiles = self.cssList;
      } else {
        searchFiles = self.jsList;
      }
      _.each(searchFiles, function(files) {
        if (!mergerFile && (_.indexOf(files, file)) !== -1) {
          return mergerFile = files[0];
        }
      });
      return mergerFile;
    },
    js: [
      {
        cookies: {
          file: '/javascripts/jquery/jquery.cookies.min.js',
          index: 0
        },
        url: {
          file: '/javascripts/jquery/jquery.url.min.js',
          index: 1
        }
      }
    ],
    css: []
  };

  _.each(MergerFiles, function(mergerInfo, mergerType) {
    var mergeList;
    if (_.isArray(mergerInfo)) {
      mergeList = [];
      _.each(mergerInfo, function(mergers) {
        var combineFileName, fileName, filePathList;
        fileName = 'vicanso';
        combineFileName = '';
        filePathList = [];
        _.each(mergers, function(fileInfo, key) {
          fileName += "_" + key;
          if (key === 'combine') {
            return combineFileName = fileInfo.file;
          } else if (fileInfo.index != null) {
            return filePathList[fileInfo.index] = fileInfo.file;
          }
        });
        if (filePathList.length !== 0) {
          if (combineFileName) {
            fileName = combineFileName;
          } else {
            fileName = "/mergers/" + fileName + "." + mergerType;
          }
          return mergeList.push([fileName].concat(_.compact(filePathList)));
        }
      });
      _.each(mergeList, function(files) {
        var content, filePath, saveFile;
        filePath = "" + (Path.dirname(__dirname)) + "/public/";
        saveFile = Path.join(filePath, files[0]);
        content = '';
        _.each(files, function(file, i) {
          if (i !== 0) {
            return content += Fs.readFileSync(Path.join(filePath, file));
          }
        });
        return Fs.writeFileSync(saveFile, content);
      });
      return MergerFiles["" + mergerType + "List"] = mergeList;
    }
  });

  delete MergerFiles.js;

  delete MergerFiles.css;

  ImportFiles = (function() {
    /**
     * [constructor description]
     * @param  {[type]} debug [description]
     * @return {[type]}       [description]
    */

    function ImportFiles(debug) {
      this.cssFiles = [];
      this.jsFiles = [];
      this.debug = debug;
      this.cssReady = false;
      this.jsReady = false;
    }

    /**
     * [importCss description]
     * @param  {[type]} path    [description]
     * @param  {[type]} prepend [description]
     * @return {[type]}         [description]
    */


    ImportFiles.prototype.importCss = function(path, prepend) {
      var self;
      self = this;
      if (self.cssReady && !self.debug) {
        return self;
      }
      self.importFiles(path, 'css', prepend);
      return self;
    };

    /**
     * [importJs description]
     * @param  {[type]} path    [description]
     * @param  {[type]} prepend [description]
     * @return {[type]}         [description]
    */


    ImportFiles.prototype.importJs = function(path, prepend) {
      var self;
      self = this;
      if (self.jsReady && !self.debug) {
        return self;
      }
      self.importFiles(path, 'js', prepend);
      return self;
    };

    /**
     * [importFiles description]
     * @param  {[type]} path    [description]
     * @param  {[type]} type    [description]
     * @param  {[type]} prepend [description]
     * @return {[type]}         [description]
    */


    ImportFiles.prototype.importFiles = function(path, type, prepend) {
      var mergerFile, self;
      self = this;
      if (_.isString(path)) {
        path = path.trim();
        if (!self.debug) {
          mergerFile = MergerFiles.getMergerFile(path, type);
          if (mergerFile) {
            path = mergerFile;
          }
        }
        if (type === 'css') {
          if ((_.indexOf(self.cssFiles, path)) === -1) {
            if (prepend) {
              self.cssFiles.unshift(path);
            } else {
              self.cssFiles.push(path);
            }
          }
        } else if ((_.indexOf(self.jsFiles, path)) === -1) {
          if (prepend) {
            self.jsFiles.unshift(path);
          } else {
            self.jsFiles.push(path);
          }
        }
      } else if (_.isArray(path)) {
        if (prepend) {
          path.reverse();
        }
        _.each(path, function(item) {
          return self.importFiles(item, type, prepend);
        });
      }
      return self;
    };

    /**
     * [exportCss description]
     * @return {[type]} [description]
    */


    ImportFiles.prototype.exportCss = function() {
      var cssFileList, self;
      self = this;
      cssFileList = [];
      _.each(self.cssFiles, function(cssFile) {
        if (cssFile.indexOf('http') !== 0) {
          cssFile = Path.join(staticPrefix, cssFile) + ("?version=" + version);
        }
        return cssFileList.push('<link rel="stylesheet" href="' + cssFile + '" type="text/css" media="screen" />');
      });
      self.cssReady = true;
      return cssFileList.join('');
    };

    /**
     * [exportJs description]
     * @return {[type]} [description]
    */


    ImportFiles.prototype.exportJs = function() {
      var jsFileList, self;
      self = this;
      jsFileList = [];
      _.each(self.jsFiles, function(jsFile) {
        if (self.debug) {
          jsFile = ('' + jsFile).replace('.min.js', '.js');
        }
        if (jsFile.indexOf('http') !== 0) {
          jsFile = Path.join(staticPrefix, jsFile) + ("?version=" + version);
        }
        return jsFileList.push('<script type="text/javascript" src="' + jsFile + '"></script>');
      });
      self.jsReady = true;
      return jsFileList.join('');
    };

    return ImportFiles;

  })();

  /**
   * [getImportObj description]
   * @param  {[type]} view [description]
   * @return {[type]}      [description]
  */


  module.exports.getImportObj = function(view) {
    if (_.isString(view)) {
      if (ImportFilesObjs[view] != null) {
        return ImportFilesObjs[view];
      } else {
        return ImportFilesObjs[view] = new ImportFiles(Config.debug);
      }
    } else {
      return new ImportFiles(Config.debug);
    }
  };

}).call(this);
